<template>
  <!-- 快速查询 -->
  <div class="col-12 padding-page q-my-sm">
    <q-form @submit="onSubmit">
      <!-- 查询例子 -->
      <div
        class="row justify-start q-pb-none"
        :style="!smallScreen ? { margin: '0 20%' } : { margin: '0 5%' }"
      >
        <span class="col-auto self-center">Input examples:</span>
        <div class="q-gutter-x-md q-gutter-y-xs">
          <q-btn
            class="text-body2"
            no-caps
            flat
            dense
            :ripple="false"
            v-for="example in searchExamples"
            :key="example.query"
            :label="example.query"
            text-color="grey-9"
            @click="queryExample(example as queryQTLParams)"
          />
        </div>
      </div>
      <!-- 查询 -->
      <q-input
        clearable
        outlined
        autofocus
        dense
        lazy-rules="ondemand"
        ref="inputRef"
        v-model="query"
        :label="t('queryForm.placeHolder')"
        :rules="inputRules"
        :style="
          !smallScreen
            ? {
                'margin-left': '20%',
                'margin-right': '20%',
                'padding-bottom': '10px',
              }
            : {
                'margin-left': '5%',
                'margin-right': '5%',
                'padding-bottom': '10px',
              }
        "
      >
        <template v-slot:after>
          <q-btn
            v-show="!smallScreen"
            round
            unelevated
            fab
            dense
            size="md"
            no-caps
            icon="search"
            color="primary"
            @click="onSubmit()"
          >
            <q-tooltip> Aggregate Search </q-tooltip>
          </q-btn>
        </template>
      </q-input>
    </q-form>
  </div>
  <!-- 信息卡片 -->
  <div class="row justify-center q-gutter-x-lg q-my-none q-px-md">
    <q-card flat bordered class="col-11 col-md q-my-xs">
      <div
        class="full-width q-px-md q-py-sm text-subtitle2 bg-secondary text-primary text-bold"
      >
        Welcome to Pancan-MNVQTLdb
      </div>
      <q-card-section
        class="row text-body2 text-foreground text-justify q-px-md q-pb-none"
      >
        <p>
          Multi-nucleotide variants (MNVs) are defined as
          <span class="text-primary text-bold q-px-xs">
            two or more nearby variants existing on the same haplotype in an
            individual. </span
          ><br />
          It has been demonstrated that MNVs are widely distributed in the human
          genome. (<a
            href="https://doi.org/10.1038/s41467-019-12438-5"
            target="_blank"
            >Wang et al. 2020</a
          >). However, the functions of MNVs, especially those located in
          non-coding regions, are largely unknown. Considering the important
          regulatory roles of SNVs, we suppose that MNVs could also affect
          molecular phenotypes by influencing regulatory elements.
        </p>
        <q-card flat class="col-11 col-md q-my-none q-py-none">
          <q-card-section
            class="col-md text-body2 text-foreground text-justify q-py-none"
          >
            <span class="text-primary text-bold rounded-borders q-px-xs"
              >In Pancan-MNVQTLdb, we: </span
            ><br />
            <ol class="no-margin q-pl-lg q-py-xs">
              <li class="q-pa-xs">
                Identified
                <span class="text-primary text-bold rounded-borders q-px-xs">{{
                  dataStat.summary.uniq_mnv
                }}</span>
                unique MNVs in 33 human cancer types and associated MNVs with
                six commonly studied molecular phenotypes;
              </li>
              <li class="q-pa-xs">
                <span>
                  Identified
                  <span class="text-primary text-bold rounded-borders q-px-xs"
                    >{{dataStat.summary.cis_qtl}}</span
                  >
                  cis- associations and
                  <span class="text-primary text-bold rounded-borders q-px-xs"
                    >{{dataStat.summary.trans_qtl}}</span
                  >
                  trans- associations;</span
                >
              </li>
              <li class="q-pa-xs">
                Identified
                <span class="text-primary text-bold rounded-borders q-px-xs"
                  >{{dataStat.survival.either}}</span
                >
                MNVQTLs associated with prognosis;
              </li>
              <li class="q-pa-xs">
                Identified
                <span class="text-primary text-bold rounded-borders q-px-xs"
                  >{{dataStat.summary.gwas}}</span
                >
                MNVQTLs associated with human complex traits and diseases;
              </li>
            </ol>
          </q-card-section>
        </q-card>
        <q-card flat class="col-11 col-md q-py-none">
          <q-card-section
            class="col-md text-body2 text-foreground text-justify q-py-none"
          >
            <span class="text-primary text-bold rounded-borders q-px-xs"
              >In Pancan-MNVQTLdb, users can: </span
            ><br />
            <ol class="no-margin q-pl-lg q-py-xs">
              <li class="q-pa-xs">
                Aggregate queries on MNVQTLs across different QTL types.
              </li>
              <li class="q-pa-xs">
                Query different types of MNVQTLs by cancer type, MNV ID, genomic
                position, or molecular phenotype.
              </li>
              <li class="q-pa-xs">
                Query survival-related MNVQTLs by cancer type, rsID, or MNV ID.
              </li>
              <li class="q-pa-xs">
                Query the MNVQTLs located in GWAS loci by QTL type, cancer type,
                rsID, or MNV ID.
              </li>
              <li class="q-pa-xs">Download all MNVQTL results.</li>
            </ol>
          </q-card-section>
        </q-card>
      </q-card-section>
      <!-- citation -->
      <q-card flat class="col-11 col-md">
        <q-card-section
          class="col-md text-body2 text-foreground text-justify q-pb-none"
        >
          <span class="text-primary text-bold rounded-borders q-px-md"
            >Citation:
          </span>
            <a class="text-subtitle2 text-primary text-bold" href="https://doi.org/10.1093/narcan/zcac043">
              Pancan-MNVQTLdb: systematic identification of multi-nucleotide
              variant quantitative trait loci in 33 cancer types
            </a>
            <q-btn flat dense rounded size="sm" icon="content_copy" @click="copyCite" />
        </q-card-section>
      </q-card>
    </q-card>
  </div>

  <!-- 功能模块 -->
  <div class="row justify-center q-gutter-x-lg q-my-none q-px-md">
    <q-card flat bordered class="col-11 col-md q-my-none">
      <div
        class="full-width q-px-md q-py-sm text-subtitle2 bg-secondary text-primary text-bold"
      >
        Modules
      </div>
      <div class="row">
        <div
          v-for="siteModule in modules"
          :key="siteModule.label"
          class="col-12 col-sm-3"
        >
          <q-btn
            :padding="smallScreen ? '0 50px 10px 50px' : '0 30px 0px 30px'"
            no-caps
            unelevated
            stretch
            class="row full-height"
            :to="{ name: siteModule.routerName }"
            :ripple="false"
            style="border: 1px solid rgb(0 0 0 / 0.03); border-radius: 0"
          >
            <div class="col-12">
              <q-img :src="siteModule.src" :ratio="16 / 9" fit="scale-down" />
            </div>
            <div
              class="col-12 full-width text-subtitle2 text-bold text-primary q-px-none"
            >
              {{ siteModule.label }}
            </div>
            <div class="col-12 full-width text-subtitle2 text-red-6 q-px-none">
              {{ siteModule.label2 }}
            </div>
          </q-btn>
        </div>
      </div>
    </q-card>
  </div>
  <div class="col-11 col-sm-12 q-px-md">
    <q-card flat bordered class="col-12 q-mt-lg" id="mnv">
      <div
        class="full-width q-px-md q-py-sm text-subtitle2 bg-secondary text-primary text-bold"
      >
        Data summary
      </div>
      <q-card-section>
        <DataCount />
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup lang="ts">
import { useQuasar, copyToClipboard } from 'quasar';
import { computed, ref, onMounted, onBeforeUnmount } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import DataCount from 'src/components/DataCount.vue';

import { getDataCounts } from 'boot/dataCount';

import type queryQTLParams from 'src/interface/queryQTLParams';

const { t } = useI18n({ useScope: 'global' });
const $q = useQuasar();
const router = useRouter();
const smallScreen = computed((): boolean => {
  return !$q.screen.gt.sm;
});

const dataStat = getDataCounts();

// 首页的图片以及导航
const modules = [
  {
    routerName: 'apaQTLPage',
    src: 'assets/index/apaqtl.png',
    label: 'apaQTL',
    label2: '(MNVs vs APA)',
  },
  {
    routerName: 'eQTLPage',
    src: 'assets/index/eqtl.png',
    label: 'eQTL',
    label2: '(MNVs vs coding gene expression)',
  },
  {
    routerName: 'lnceQTLPage',
    src: 'assets/index/lncqtl.png',
    label: 'lncRNA-eQTL',
    label2: '(MNVs vs lncRNA expression)',
  },
  {
    routerName: 'mireQTLPage',
    src: 'assets/index/mirqtl.png',
    label: 'miRNA-eQTL',
    label2: '(MNVs vs miRNA expression)',
  },
  {
    routerName: 'meQTLPage',
    src: 'assets/index/meqtl.png',
    label: 'meQTL',
    label2: '(MNVs vs methylation)',
  },
  {
    routerName: 'sQTLPage',
    src: 'assets/index/sqtl.png',
    label: 'sQTL',
    label2: '(MNVs vs splicing)',
  },
  {
    routerName: 'SurvivalPage',
    src: 'assets/index/survival.jpg',
    label: 'Survival-QTL',
    label2: '(MNVs vs survival)',
  },
  {
    routerName: 'GWASPage',
    src: 'assets/index/gwas.svg',
    label: 'GWAS-QTL',
    label2: '(MNVQTLs in GWAS loci)',
  },
];

// 表单查询相关
const inputRef = ref(null);
// 表单字段
const query = ref('');
const bytrait = ref(0);
const bypos = ref(0);
const trans = ref(0);
// 验证规则
const inputRules = [
  (val) => {
    const containSpecial = (s: string) => {
      var containSpecial = RegExp(
        /[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\.)(\/)(\<)(\>)(\?)(\)]+/
      );
      return containSpecial.test(s);
    };
    // 空值
    if (val === null) {
      val = '';
    }
    const isEmpty = val === '';
    // 判断是不是rsid
    const matchedRsid = val.match(/^rs/);
    // 单个位置
    const matchedSinglePos = val.match(/^[chr]{0,}(\d{1,2}):(\d+)$/);
    const singlePosCorrect =
      matchedSinglePos !== null
        ? Number(matchedSinglePos[1]) > 0 &&
          Number(matchedSinglePos[1]) < 23 &&
          Number(matchedSinglePos[2]) > 0
        : null;
    // 两个位置
    const matchedDoublePos = val.match(/^[chr]{0,}(\d{1,2}):(\d+)-(\d+)$/);
    const doublePosCorrect =
      matchedDoublePos !== null
        ? Number(matchedDoublePos[1]) > 0 &&
          Number(matchedDoublePos[1]) < 23 &&
          Number(matchedDoublePos[2]) > 0 &&
          Number(matchedDoublePos[3]) > 0 &&
          Number(matchedDoublePos[3]) >= Number(matchedDoublePos[2])
        : null;

    if (isEmpty) {
      // 空值
      return t('queryForm.allertMessages.empty');
    } else if (matchedRsid) {
      // rsid
      query.value = val;
      bytrait.value = 0;
      bypos.value = 0;
      return true;
    } else if (matchedSinglePos) {
      // 单位置
      if (singlePosCorrect) {
        query.value = `chr${matchedSinglePos[1]}:${matchedSinglePos[2]}-${matchedSinglePos[2]}`;
        bypos.value = 1;
        bytrait.value = 0;
        return true;
      } else {
        return t('queryForm.allertMessages.wrongPos');
      }
    } else if (matchedDoublePos) {
      // 双位置
      if (doublePosCorrect) {
        query.value = `chr${matchedDoublePos[1]}:${matchedDoublePos[2]}-${matchedDoublePos[3]}`;
        bypos.value = 1;
        bytrait.value = 0;
        return true;
      } else {
        return t('queryForm.allertMessages.wrongPos');
      }
    } else if (val.match(/^cg\d+$/)) {
      // 探针
      bytrait.value = 1;
      bypos.value = 0;
      return true;
    } else if (!containSpecial(val)) {
      query.value = val.toUpperCase();
      bytrait.value = 1;
      bypos.value = 0;
      return true;
    } else {
      // 不包含特殊字符
      return t('queryForm.allertMessages.hasSpecial');
    }
  },
];
// 查询函数
const onSubmit = () => {
  inputRef.value.validate();
  if (!inputRef.value.hasError) {
    router.push({
      name: 'ResultsPage',
      query: {
        query: query.value,
        bypos: bypos.value,
        bytrait: bytrait.value,
        trans: trans.value,
      },
    });
  }
};

// 轮播提示语
const index = ref(0);
const hint_message = ref(t('queryForm.example') + ' ' + 'rs7144811');
const message_list = ['rs7144811', 'NPIPB15', 'chr16:70580000-70590000'];
let timer: NodeJS.Timeout;

onMounted(() => {
  timer = setInterval(() => {
    if (index.value >= message_list.length) {
      index.value = 0;
    }
    hint_message.value =
      t('queryForm.example') + ' ' + message_list[index.value];
    index.value += 1;
  }, 3000);
});
onBeforeUnmount(() => {
  clearTimeout(timer);
});

// 查询示例
const searchExamples = [
  {
    query: 'rs7144811',
    bypos: 0,
    bytrait: 0,
  },
  {
    query: 'rs7143432,rs7144811',
    bypos: 0,
    bytrait: 0,
  },
  {
    query: 'chr16:70580000-70590000',
    bypos: 1,
    bytrait: 0,
  },
  {
    query: 'NPIPB15',
    bypos: 0,
    bytrait: 1,
  },
];
const queryExample = (params: queryQTLParams) => {
  router.push({
    name: 'ResultsPage',
    query: {
      query: params.query,
      bypos: params.bypos,
      bytrait: params.bytrait,
    },
  });
};

const copyCite = () => {
  const cite =
    'Wang D, Cao W, Yang W, Jin W, Luo H, Niu X, Gong J. Pancan-MNVQTLdb: systematic identification of multi-nucleotide variant quantitative trait loci in 33 cancer types. NAR Cancer. 2022 Dec 22;4(4):zcac043. doi: 10.1093/narcan/zcac043. PMID: 36568962; PMCID: PMC9773367.';
  copyToClipboard(cite)
    .then(() => {
      $q.notify({
        message: 'Citation has been copyed to clipboard',
        icon: 'check',
        type: 'positive',
        timeout: 500,
      });
    })
    .catch(() => {
      // fail
    });
};
</script>

<style scoped lang="scss"></style>
